package com.vg.leftmenu;

import java.util.ArrayList;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.os.SystemClock;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

import com.androidhive.jsonparsing.JSONParser;
import com.androidhive.jsonparsing.MyAdapter;
import com.androidhive.jsonparsing.R;
import com.vg.config.linkUrl;
import com.vg.library.Httppostaux;
import com.vg.service.ServiceCity;
import com.vg.service.ServiceGender;
import com.vg.service.ServiceUserType;
import com.vg.spinner.City;
import com.vg.spinner.Student;

public class Register extends Activity {

	static Spinner spGender, spTinhtrang;
	// ServiceGender mServiceGender;

	ArrayList<Student> arrayList = new ArrayList<Student>();
	JSONArray contacts, contact_city;
	private ArrayList<Student> array;
	ArrayList<City> city_array;

	MyAdapter adapter;
	JSONParser jparse;
	ServiceCity mCity_service;
	linkUrl mLinkUrl;
	ServiceGender mServiceGender;
	ServiceUserType mServiceUserType;
	JSONArray jsa;

	Button bt_ok, bt_cancel;
	static EditText edt_hoten, edt_email, edt_phone, edt_password, edt_repass,edt_date;
	static String name;
	static String email;
	static String pass;
	static String phone;
	static String repass;
	static String date;
	
	String[] array_spgender={"Chọn Giới Tính","Nam","Nữ","Gay","Lesbian"};

	Httppostaux post;
	// /ServiceCity svCity;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		getWindow().setSoftInputMode(
				WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_register);
		post=new Httppostaux();
		spGender = (Spinner) findViewById(R.id.register_spinnerSex);
		bt_ok = (Button) findViewById(R.id.register_btnOK);
		bt_cancel = (Button) findViewById(R.id.register_btncancel);
		edt_email = (EditText) findViewById(R.id.edt_email);
		edt_hoten = (EditText) findViewById(R.id.edt_name);
		edt_password = (EditText) findViewById(R.id.edt_pass);
		edt_phone = (EditText) findViewById(R.id.edt_phone);
		edt_repass = (EditText) findViewById(R.id.edt_repass);
		edt_date=(EditText)findViewById(R.id.edt_birthday);

		mServiceGender = new ServiceGender();
		mLinkUrl = new linkUrl();
		spTinhtrang = (Spinner) findViewById(R.id.register_spinnerStatus);
		mServiceUserType = new ServiceUserType();

		drop_gender(spGender, mLinkUrl.gender, mServiceGender.dropSpinner());
		drop_gender(spTinhtrang, mLinkUrl.user_type,
				mServiceUserType.dropSpinner());

		bt_ok.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				Toast.makeText(getApplicationContext(), edt_hoten.getText(),
						Toast.LENGTH_SHORT).show();
				get_data_edittext();
				// TODO Auto-generated method stub
				if (name.equals("") || email.equals("") || pass.equals("") || phone.equals("")) {
					Toast.makeText(getApplicationContext(), "Hãy Nhập Đủ Thông Tin",
							Toast.LENGTH_SHORT).show();
				}
				else if (!pass.equals(repass)) {
					Toast.makeText(getApplicationContext(), "Password Không Trùng Nhau!",
							Toast.LENGTH_SHORT).show();
				}
				// else if (edt_password.getText()!=edt_repass.getText()) {
				// Toast.makeText(getApplicationContext(),
				// "Nhập Mật Khẩu Không Đúng!",Toast.LENGTH_SHORT)
				// .show();
				// }
				else {
					Toast.makeText(getApplicationContext(),
							"ok", Toast.LENGTH_SHORT).show();
					
					

					// TODO Auto-generated method stub
//					String etName.getText();
//					etPhone.getText();
//					spGender.getSelectedItemPosition();
//					spCity.getSelectedItemPosition();
//					spBodyType.getSelectedItemPosition();
//					spColor.getSelectedItemPosition();
//					spDrinker.getSelectedItemPosition();
//					spEducation.getSelectedItemPosition();
//					spHeight.getSelectedItemPosition();
//					spMaritalStatus.getSelectedItemPosition();
//					spReligion.getSelectedItemPosition();
//					spSmoker.getSelectedItemPosition();
//					spUserType.getSelectedItemPosition();
//					spWeight.getSelectedItemPosition();

					//	ProgressDialog progDialog = new ProgressDialog(this);
					//	progDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
					//	progDialog.setMessage("Logging in ...");
				//		progDialog.show();
		//
						// Extreamos datos de los EditText
						//String username = user.getText().toString();
						//String password = pass.getText().toString();
					get_data_edittext();
						int logstatus = -1;
						int gender=spGender.getSelectedItemPosition();
						int user_type=spTinhtrang.getSelectedItemPosition();
						String gender_str=String.valueOf(gender);
						String user_type_str=String.valueOf(user_type);
						Log.i("date", ""+spGender.getItemAtPosition(2));
						
						Log.i("1", gender_str);
						Log.i("2", user_type_str);
						Log.i("3", name);
						Log.i("4", name);

						/*
						 * Creamos un ArrayList del tipo nombre valor para agregar los
						 * datos recibidos por los parametros anteriores y enviarlo
						 * mediante POST a nuestro sistema para relizar la validacion
						 */
						ArrayList<NameValuePair> postparameters2send = new ArrayList<NameValuePair>();

						postparameters2send.add(new BasicNameValuePair("r_name",
								name));
						postparameters2send.add(new BasicNameValuePair("r_email",
								email));
						postparameters2send.add(new BasicNameValuePair("r_phone",
								phone));
						postparameters2send.add(new BasicNameValuePair("r_pass",
								pass));
						postparameters2send.add(new BasicNameValuePair("r_gender",
								gender_str));
						postparameters2send.add(new BasicNameValuePair("user_type",
								user_type_str));
						postparameters2send.add(new BasicNameValuePair("r_date",
								"06/06/2012"));
						

						// realizamos una peticion y como respuesta obtenes un array
						// JSON
						JSONObject jdata = post.getserverdata_object(postparameters2send,
								"http://deduocyeu.com/json/addUser.php");

						/*
						 * como estamos trabajando de manera local el ida y vuelta sera
						 * casi inmediato para darle un poco realismo decimos que el
						 * proceso se pare por unos segundos para poder observar el
						 * progressdialog la podemos eliminar si queremos
						 */
						SystemClock.sleep(950);

						// si lo que obtuvimos no es null
						if (jdata != null && jdata.length() > 0) {

							JSONObject json_data; // creamos un objeto JSON
							try {
//							/	json_data = jdata.getJSONObject(0); // leemos el primer
																	// segmento en
																	// nuestro caso el
																	// unico
								logstatus = jdata.getInt("status");// accedemos
																			// al valor
								// String user=json_data.getString("user");
								//JSONObject user_obj = jdata.getJSONObject("user");

//								id = user_obj.getString("use_id");
//								use_login=user_obj.getString("use_login");
//								fullname=user_obj.getString("use_fullname");
//								picture=user_obj.getString("use_avatar");
//								Log.i("Userobj", "" + id);
								Log.e("loginstatus", "logstatus= " + logstatus);// muestro
																				// por
																				// log
																				// que
																				// obtuvimos
							} catch (JSONException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}

							// validamos el valor obtenido
							if (logstatus == 0) {// [{"logstatus":"0"}]
								Log.e("loginstatus ", "invalido");
							//	err_login();
								// return false;
							} else {						
								// [{"logstatus":"1"}]						
								    	Log.e("loginstatus ", "valido");
								    	Toast.makeText(getApplicationContext(), "Đăng Ký Thành Công", Toast.LENGTH_SHORT).show();
								    	reset_data_edittext();
//										Intent i = new Intent(Login.this,
//													Activity_ChatIndex.class);
//											String use="tuan".toString();
//											i.putExtra("use_id", id);
//											i.putExtra("use_login", use);
//											i.putExtra("use_fullname", fullname);
//											i.putExtra("use_avatar", picture);
//											startActivity(i);
								     //   progDialog.dismiss();							
								// return true;
							}

						} else { // json obtenido invalido verificar parte WEB.
							Log.e("JSON  ", "ERROR");
							// return false;
						}
						// verificamos si estan en blanco
						// if( checklogindata( usuario , passw )==true){
						// //si pasamos esa validacion ejecutamos el asynctask pasando
						// el usuario y clave como parametros
						// new asynclogin().execute(usuario,passw);
						//
						// }else{
						// //si detecto un error en la primera validacion vibrar y
						// mostrar un Toast con un mensaje de error.
						// err_login();
						// }

					
				
				}

			}
		});

		bt_cancel.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub
				
			}
		});
	}

	public void drop_gender(Spinner sp, String url, ArrayList<Student> arr) {

		jparse = new JSONParser();
		mCity_service = new ServiceCity();
		array = new ArrayList<Student>();
		arrayList = mCity_service.dropSpinner();

		// spinner.setAdapter(adapter);
		jsa = jparse.getJsonarray(url);
		// contact_city=jparse.getJsonarray(url_city);
		adapter = new MyAdapter(this, R.layout.drop_gender, arr, true);
		sp.setAdapter(adapter);
		for (int i = 0; i < jsa.length(); i++) {
			try {
				Student student;
				student = new Student(jsa.getString(i));
				array.add(student);
				Log.i("Array", "" + array);

			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		adapter.notifyDataSetChanged();
	}
	
	static void get_data_edittext()
	{
		date=""+edt_date.getText();
		 name = "" + edt_hoten.getText();
		 email= "" + edt_email.getText();
		 pass= "" + edt_password.getText();
		 phone= "" + edt_phone.getText();
		 repass=""+edt_repass.getText();
	}
	
	static void reset_data_edittext()
	{
		edt_email.setText("");
		edt_hoten.setText("");
		edt_password.setText("");
		edt_phone.setText("");
		edt_repass.setText("");
		spGender.setSelection(0);
		spTinhtrang.setSelection(0);
		edt_date.setText("");
	}

}
